package com.sec.etech.ism.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sec.etech.common.constant.DBConstant;
import com.sec.etech.ism.constant.SignatureConstant;
import com.sec.etech.ism.service.IsmMethodService;
import com.sec.etech.ism.service.IsmTaskService;
import com.sec.etech.sys.util.DbUtil;
import lombok.extern.slf4j.Slf4j;
import org.openbpm.base.api.exception.BusinessMessage;
import org.openbpm.base.core.util.StringUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class IsmGetNcNumsByPartsServiceImpl implements IsmMethodService {
    @Resource
    IsmTaskService ismTaskService;

    @Override
    public JSONObject call(String sysCode, String serviceCode, JSONObject businessParams) throws Exception{
        JSONObject result = new JSONObject();
        this.checkAndGetData(businessParams);
        List resData = this.getNcNumsByParts(businessParams.getJSONObject(SignatureConstant.INPUT_PARAMS));
        ismTaskService.deleteTaskByParams(sysCode, serviceCode, serviceCode, null,
                businessParams.getString(SignatureConstant.INPUT_PARAMS));
        result.put("flag", "success");
        result.put("data", resData);
        return result;
    }

    //入参检查
    private void checkAndGetData(JSONObject busParams) throws BusinessMessage{
        JSONObject object = busParams.getJSONObject(SignatureConstant.INPUT_PARAMS);
        String partsNum = object.getString("partsNum");
        String machineNum = object.getString("machineNum");
        if(StringUtil.isEmpty(partsNum)){
            throw new BusinessMessage("请求中缺少零件图号（partsNum）参数，请检查！");
        }
        if(StringUtil.isEmpty(machineNum)){
            throw new BusinessMessage("请求中缺少设备编号（machineNum）参数，请检查！");
        }
    }
    //获取程序编号
    private List<Map<String,Object>> getNcNumsByParts(JSONObject object) throws Exception {
        JdbcTemplate slaveJdbcTemplate = DbUtil.getJdbcTemplate(DBConstant.ETECH_SLAVE);
        String partsNum = object.getString("partsNum");
        String machineNum = object.getString("machineNum");

        String sql = "select t1.ncNum from proc_nc t1, proc_nc_z_machine t2 " +
                "where t1.machineid=t2.machineid and t1.active=1 and t2.machinenum like ? and t1.statusid in (2, 4) " +
                " and t1.ncplanid in (select ncplanid from proc_nc_ncplan where active=1 " +
                "  and ((partsid=(select partsid from prod_parts where active=1 and partsnum=?) and partsid>0) or partsnum=?))";
        List<Map<String,Object>> ncList = slaveJdbcTemplate.queryForList(sql, "%" + machineNum + "%", partsNum, partsNum);
        return ncList;
    }

    @Override
    public String methodName(){
        return "getNcNumsByParts";
    }
}
